package com.kldy8.kldyw.logre;


import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


import com.kldy8.kldyw.R;
import com.kldy8.kldyw.SystemSet;
import com.kldy8.kldyw.release.util.ToastUtil;
import com.kldy8.kldyw.sharedpreference.SharedPreUtil;
import com.kldy8.kldyw.sharedpreference.UserEntity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Request;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>
{
    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
//    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private ActionBar actionBar ;
    private Button mEmailSignInButton;
    private Button forget_btn;

    private ImageButton qq_btn;
    private ImageButton wechat_btn;
    private ImageButton weibo_btn;

//    private int now_chooes = 0;

    String client_key ;

    MyCallBack myCallBack =  new MyCallBack()
    {
        public boolean getResult(int result)
        {
            showProgress(false);
            if (result == 1)
            {
                Intent in = new Intent();
                in.putExtra( "result", "res" );
                int abc = 1003;
                setResult(abc, in );
                finish();
            }
            else if(result == 10002)
            {
                Toast.makeText(LoginActivity.this,"用户不存在",Toast.LENGTH_LONG).show();
            }
            else if(result == 10003)
            {
                Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_LONG).show();

            }
            else if(result == 400)
            {
                Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_LONG).show();
            }
            else  if(result == -1)
            {
                Toast.makeText(LoginActivity.this,getResources().getString(R.string.error_net_system),Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_LONG).show();
            }
            return true;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        client_key = tm.getDeviceId();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        qq_btn= (ImageButton) findViewById(R.id.qq_btn);
        wechat_btn= (ImageButton) findViewById(R.id.wechat_btn);
        weibo_btn= (ImageButton) findViewById(R.id.weibo_btn);


        qq_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                now_chooes = 1;
                Toast.makeText(LoginActivity.this,"QQ第三方登录还未开放，待续。。。",Toast.LENGTH_LONG).show();

//                Platform weibo = ShareSDK.getPlatform(QQ.NAME);
//                weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
//                weibo.setPlatformActionListener(LoginActivity.this); // 设置分享事件回调
//
//                weibo.authorize();//单独授权
//                weibo.showUser(null);//授权并获取用户信息


            }
        });

        wechat_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                now_chooes = 2;
//                Platform wetchat = ShareSDK.getPlatform(Wechat.NAME);
//                    if (wetchat == null) {
//                        return;
//                    }
//                    if (wetchat.isAuthValid()) {
//                        wetchat.removeAccount(true);
//                        return;
//                    }
//                    wetchat.SSOSetting(false);  //设置false表示使用SSO授权方式
//                    wetchat.setPlatformActionListener(LoginActivity.this); // 设置分享事件回调
//
//                    wetchat.authorize();//单独授权
//                    wetchat.showUser(null);//授权并获取用户信息
                login(Wechat.NAME);
            }
        });

        weibo_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                login(SinaWeibo.NAME);

//                now_chooes = 3;
//                Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
//
//                if (weibo == null) {
//                    return;
//                }
//                if (weibo.isAuthValid()) {
//                    weibo.removeAccount(true);
//                    return;
//                }
//                //使用SSO授权，通过客户单授权
//                weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
//                weibo.setPlatformActionListener(LoginActivity.this); // 设置分享事件回调
//                weibo.showUser(null);//授权并获取用户信息

            }
        });



        forget_btn= (Button) findViewById(R.id.forgetPwd_btn);
        forget_btn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i=new Intent();
                i.setClass(LoginActivity.this, ForgetpwdActivity.class);
                startActivity(i);
                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

            }
        });
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.user_name_tv);
        populateAutoComplete();

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

    }
    /**
     * 登录
     *
     * @throws
     */
    private void loginBtn(final String phone, final String password , final MyCallBack myCallBack)
    {
        Log.e("phone",phone);
        Log.e("password",password);


        ServerApi.login(phone,password,client_key ,new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                Log.e("onError",e.getMessage());
                myCallBack.getResult(0);
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("......",response.toString());
                JSONObject jsonObject = new JSONObject(response);
                if ("0".equals(jsonObject.optString("code")))
                {
                    myCallBack.getResult(1);
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    String username =  objectData.optString("username");
                    String token =  objectData.optString("token");
                    String member_id =  objectData.optString("member_id");
                    String f_person =  objectData.optString("f_person");
                    String auth_personal =  objectData.optString("auth_personal");
                    String auth_enterprise =  objectData.optString("auth_enterprise");
                    String auth_actor =  objectData.optString("auth_actor");
                    String auth_writer =  objectData.optString("auth_writer");


                    SharedPreUtil.getInstance();
                    if (SharedPreUtil.getInstance() ==  null)
                    {
                        SharedPreUtil.initSharedPreference(getApplicationContext());
                    }
                    UserEntity entity = SharedPreUtil.getInstance().getUser();
                    entity.setUserName(phone);
                    entity.setPassword(password);
                    SharedPreUtil.getInstance().putUser(entity);

                    SystemSet.getInstance().setToken(token);
                    SystemSet.getInstance().setMember_id(member_id);
                    SystemSet.getInstance().setF_person(f_person);
                    SystemSet.getInstance().setAuth_personal(auth_personal);
                    SystemSet.getInstance().setAuth_enterprise(auth_enterprise);
                    SystemSet.getInstance().setAuth_actor(auth_actor);
                    SystemSet.getInstance().setAuth_writer(auth_writer);
                }
                else  if ("10003".equals(jsonObject.optString("code")))
                {
                    myCallBack.getResult(10003);
                }
                else  if ("10008".equals(jsonObject.optString("code")))
                {
                    myCallBack.getResult(10008);
                }
                else  if ("10002".equals(jsonObject.optString("code")))
                {
                    myCallBack.getResult(10002);
                }
                else
                {
                    myCallBack.getResult(-1);
                }
            }
        });
    }
    private void populateAutoComplete()
    {
        if (!mayRequestContacts())
        {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
//        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
//            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
//                    .setAction(android.R.string.ok, new View.OnClickListener() {
//                        @Override
//                        @TargetApi(Build.VERSION_CODES.M)
//                        public void onClick(View v) {
//                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
//                        }
//                    });

//        }
//    else {
//            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
//        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin()
    {
        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email))
        {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        }
//        else if (!TextUtil.isMobileNumber(email)&&)
//        {
//            mEmailView.setError(getString(R.string.error_invalid_email));
//            focusView = mEmailView;
//            cancel = true;
//        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);

            loginBtn(email,password,myCallBack);

        }
    }



    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    /**
     * TODO 跳转dialog
     */
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Phone
                .NUMBER},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if(null==cursor){
            return;
        }
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }



    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }


    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.login_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            this.finish();
        }
        if (id == R.id.action_register)
        {
            Intent intent = new Intent();
            intent.setClass(this, RegisterActivity.class);
            startActivity(intent);
            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
    }


//    @Override
//    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap)
//    {
//        //用户资源都保存到res
//        //通过打印res数据看看有哪些数据是你想要的
//        if (action == Platform.ACTION_USER_INFOR)
//        {
//            PlatformDb platDB = platform.getDb();//获取数平台数据DB
//            //通过DB获取各种数据
//            String assestoken =  platDB.getToken();
//            String userGender =  platDB.getUserGender();
//            String userIcon = platDB.getUserIcon();
//            String userId = platDB.getUserId();
//            String userName = platDB.getUserName();
//
//            Log.e("TAG","token:"+assestoken+",userGender:"+userGender+",userIcon:"+userIcon+",usetId:"+userId+",userName:"+userName);
//            Toast.makeText(LoginActivity.this,"token:"+assestoken+",userGender:"+userGender+",userIcon:"+userIcon+",usetId:"+userId+",userName:"+userName,Toast.LENGTH_LONG).show();
//

//
//            if (now_chooes == 1)
//            {
//                Toast.makeText(LoginActivity.this,"QQ第三方登录还未开放，待续。。。",Toast.LENGTH_LONG).show();
//            }
//            else if (now_chooes == 2)
//            {
//                ServerApi.wechat(assestoken, userId, client_key, new ServerCallBack() {
//                    @Override
//                    public void onError(Request request, Exception e) {
//                        Log.e("onError",e.getMessage());
//                        myCallBack.getResult(0);
//                    }
//
//                    @Override
//                    public void onResponse(String response) throws JSONException
//                    {
//                        Log.e("......",response.toString());
////                            Toast.makeText(LoginActivity.this,response.toString(),Toast.LENGTH_LONG).show();
//                        JSONObject jsonObject = new JSONObject(response);
//                        if ("0".equals(jsonObject.optString("code")))
//                        {
//                            JSONObject objectData = jsonObject.optJSONObject("data");
//                            String username =  objectData.optString("username");
//                            String token =  objectData.optString("token");
//                            String member_id =  objectData.optString("member_id");
//                            String f_person =  objectData.optString("f_person");
//                            String auth_personal =  objectData.optString("auth_personal");
//                            String auth_enterprise =  objectData.optString("auth_enterprise");
//                            String auth_actor =  objectData.optString("auth_actor");
//                            String auth_writer =  objectData.optString("auth_writer");
//
//
//                            SharedPreUtil.getInstance();
//                            if (SharedPreUtil.getInstance() ==  null)
//                            {
//                                SharedPreUtil.initSharedPreference(getApplicationContext());
//                            }
//
//                            SystemSet.getInstance().setToken(token);
//                            SystemSet.getInstance().setMember_id(member_id);
//                            SystemSet.getInstance().setF_person(f_person);
//                            SystemSet.getInstance().setAuth_personal(auth_personal);
//                            SystemSet.getInstance().setAuth_enterprise(auth_enterprise);
//                            SystemSet.getInstance().setAuth_actor(auth_actor);
//                            SystemSet.getInstance().setAuth_writer(auth_writer);
//                            myCallBack.getResult(1);
//                            return;
//
//                        }
//                        else  if ("10003".equals(jsonObject.optString("code")))
//                        {
//                            myCallBack.getResult(10003);
//                        }
//                        else  if ("10008".equals(jsonObject.optString("code")))
//                        {
//                            myCallBack.getResult(10008);
//                        }
//                        else  if ("10032".equals(jsonObject.optString("code")))
//                        {
//                            Intent intent = new Intent();
//                            intent.setClass(LoginActivity.this, ThreadRegisterActivity.class);
//                            intent.putExtra("register_way","wechat");
//                            startActivity(intent);
//                            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//                            return;
//                        }
//                        else
//                        {
//                            myCallBack.getResult(-1);
//                        }
//                    }
//                });
//            }
//            else if (now_chooes == 3)
//            {
//                if (action == Platform.ACTION_USER_INFOR) {
//                    Message msg = new Message();
//                    msg.what = MSG_AUTH_COMPLETE;
//                    msg.arg2 = action;
//                    handler.sendMessage(msg);
//                }
//            }
//
//        }
//    }

    final  int MSG_AUTH_COMPLETE = 33333;

//    @Override
//    public void onError(Platform platform, int i, Throwable throwable)
//    {
//
//    }
//
//    @Override
//    public void onCancel(Platform platform, int i)
//    {
//
//    }

    class MyCallBack
    {
        //0不成功 1成功
        public boolean getResult(int result){
            return false;
        };
    }

//    private Handler handler = new Handler()
//    {
//        @Override
//        public void handleMessage(Message msg)
//        {
//            super.handleMessage(msg);
//
//            String   assestoken = SystemSet.getInstance().getAssestoken();
//            String   userId = SystemSet.getInstance().getUserId();
//            Toast.makeText(LoginActivity.this,"我收到了信息",Toast.LENGTH_LONG).show();
//
//
//            ServerApi.weibo(assestoken, userId, client_key, new ServerCallBack()
//            {
//                @Override
//                public void onError(Request request, Exception e)
//                {
//                    Log.e("onError",e.getMessage());
//                    myCallBack.getResult(0);
//                }
//
//                @Override
//                public void onResponse(String response) throws JSONException
//                {
//                    Log.e("......",response.toString());
//                    Toast.makeText(LoginActivity.this,response.toString(),Toast.LENGTH_LONG).show();
//                    JSONObject jsonObject = new JSONObject(response);
//                    if ("0".equals(jsonObject.optString("code")))
//                    {
//                        JSONObject objectData = jsonObject.optJSONObject("data");
//                        String username =  objectData.optString("username");
//                        String token =  objectData.optString("token");
//                        String member_id =  objectData.optString("member_id");
//                        String f_person =  objectData.optString("f_person");
//                        String auth_personal =  objectData.optString("auth_personal");
//                        String auth_enterprise =  objectData.optString("auth_enterprise");
//                        String auth_actor =  objectData.optString("auth_actor");
//                        String auth_writer =  objectData.optString("auth_writer");
//
//
//                        SharedPreUtil.getInstance();
//                        if (SharedPreUtil.getInstance() ==  null)
//                        {
//                            SharedPreUtil.initSharedPreference(getApplicationContext());
//                        }
//
//                        SystemSet.getInstance().setToken(token);
//                        SystemSet.getInstance().setMember_id(member_id);
//                        SystemSet.getInstance().setF_person(f_person);
//                        SystemSet.getInstance().setAuth_personal(auth_personal);
//                        SystemSet.getInstance().setAuth_enterprise(auth_enterprise);
//                        SystemSet.getInstance().setAuth_actor(auth_actor);
//                        SystemSet.getInstance().setAuth_writer(auth_writer);
//                        myCallBack.getResult(1);
//                        return;
//
//                    }
//                    else  if ("10003".equals(jsonObject.optString("code")))
//                    {
//                        myCallBack.getResult(10003);
//                    }
//                    else  if ("10008".equals(jsonObject.optString("code")))
//                    {
//                        myCallBack.getResult(10008);
//                    }
//                    else  if ("10032".equals(jsonObject.optString("code")))
//                    {
//                        Intent intent = new Intent();
//                        intent.setClass(LoginActivity.this, ThreadRegisterActivity.class);
//                        intent.putExtra("register_way","wechat");
//                        startActivity(intent);
//                        overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//                        return;
//                    }
//                    else
//                    {
//                        myCallBack.getResult(-1);
//                    }
//                }
//            });
//        }
//    };


    private void login(String platformName)
    {
        LoginApi api = new LoginApi();
        //设置登陆的平台后执行登陆的方法
        api.setPlatform(platformName);
        showProgress(true);
        api.setOnLoginListener(new OnLoginListener()
        {
            public boolean onLogin(String platform, HashMap<String, Object> res)
            {
                showProgress(false);
                // 在这个方法填写尝试的代码，返回true表示还不能登录，需要注册
                // 此处全部给回需要注册
                myCallBack.getResult(1);
                return true;
            }

            public boolean onRegister(UserInfo info)
            {
                showProgress(false);
                // 填写处理注册信息的代码，返回true表示数据合法，注册页面可以关闭
                Toast.makeText(LoginActivity.this,"onRegister",Toast.LENGTH_LONG).show();
                Toast.makeText(LoginActivity.this,LoginActivity.this.getString(R.string.fa),Toast.LENGTH_LONG).show();

                Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, ThreadRegisterActivity.class);
                            intent.putExtra("register_way","wechat");
                            startActivity(intent);
                            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

                return true;
            }

            @Override
            public void onError(int code)
            {
                showProgress(false);
                myCallBack.getResult(code);
            }
        });
        api.login(this);
    }
}


